//
//  URL+Extension.swift
//  Poetry
//
//  Created by cheyongzi on 2023/12/14.
//

import Foundation

extension URL{
    public var queryDic: [String: String]? {
        guard
            let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
            let queryItems = components.queryItems else { return nil }
        return queryItems.reduce(into: [String: String]()) { (result, item) in
            result[item.name] = item.value
        }
    }
    
    public var mainURL: String? {
        guard let schema = self.scheme,let host = self.mainHost else {
            return nil
        }
        return schema + "://"+host + self.mainPath
    }
    
    public func addQuery(_ params: [String: String])-> String?{
        guard let urlStr = mainURL else {
            return nil
        }
        var queryItems: [URLQueryItem] = []
        params.forEach { key,value in
            queryItems.append(URLQueryItem.init(name: key, value: value))
        }
        var urlComponents = URLComponents.init(string: urlStr)
        if queryItems.count > 0 {
            urlComponents?.queryItems = queryItems
        }
        return urlComponents?.url?.absoluteString
    }
    
    public func replacePath(_ replace:String)->String?{
        if replace == self.path {
            return nil
        }
        guard let schema = self.scheme,let host = self.mainHost else {
            return nil
        }
        var result = schema+"://"+host
        let replacePath = replace.hasPrefix("/") ? replace : ("/"+replace)
        result+=replacePath
        if let query = self.queryStr{
            result += query
        }
        return result
    }
    
    public var mainUri: String?{
        var result = self.mainPath
        if let query = self.queryStr{
            result += query
        }
        return result
    }
    
    public var mainHost: String? {
        guard var host = self.host else {
            return nil
        }
        if let port = self.port {
            host+=(":"+"\(port)")
        }
        return host
    }
    
    public var queryStr: String? {
        guard var query = self.query else {
            return nil
        }
        if !query.hasPrefix("?") {
            query = "?"+query
        }
        return query
    }
    
    public var mainPath: String {
        let urlStr = self.absoluteString
        var path = self.path
        if path.isEmpty {
            return path
        }
        if let endIndex = urlStr.endIndex(of: path),urlStr.suffix(from: endIndex).hasPrefix("/") {
            path+="/"
        }
        if !path.hasPrefix("/"){
            path = "/"+path
        }
        return path
    }
    
    public static func encode(string: String?)-> URL?{
        guard let encodeStr = string?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            return nil
        }
        return URL.init(string: encodeStr)
    }
}
